﻿using System.Collections.Generic;
using System.Linq;
using Loki.Utils;
using Luna.Data.Common;
using Luna.Data.Crm;
using Luna.Model.Common;
using Luna.Model.Connector;

namespace Luna.Model.Crm
{
    internal class CrmService : LokiService, ICrmService
    {
        public ICrmDataProvider DataProvider { get; set; }

        public IGeolocalizer Localizer { get; set; }

        public IEnumerable<IEntity> Entities
        {
            get { return DataProvider.EntitiesGetAll().Select(x => new Entity(x)); }
        }

        public void Save(IEditableEntity entity)
        {
            EditableEntity convertedEntity = entity as EditableEntity;
            if (convertedEntity != null)
            {
                var geoloc = Localizer.Localize(convertedEntity);
                DataProvider.EntitySave(convertedEntity.Data);

                if (geoloc != null)
                {
                    ///DataProvider.GeolocalisationDelete(convertedEntity.Data.PK);
                    var locData = Context.Get<IGeolocalisationData>();
                    locData.Latitude = geoloc.Latitude;
                    locData.Longitude = geoloc.Longitude;
                    locData.PK = convertedEntity.Data.PK;

                    //DataProvider.GeolocalisationSave(locData);
                }
            }
        }

        public IGeoData GetLocalization(IEditableEntity entity)
        {
            EditableEntity convertedEntity = entity as EditableEntity;
            if (convertedEntity != null)
            {
                //return DataProvider.GeolocalisationGet(entity.ID);
            }

            return null;
        }
    }
}